﻿using System.Linq;

namespace System.Management.HyperV
{
    public sealed class Job : IDisposable
    {
        private readonly ManagementObject _TheJob;

        public Job(ManagementObject job)
        {
            this._TheJob = job;
        }

        internal ManagementObject RawJob
        {
            get { return this._TheJob; }
        }

        #region Properties
        public JobState State
        {
            get
            {
                this._TheJob.Get();
                return (JobState)this._TheJob.Properties["JobState"].Value;
            }
        }

        public decimal PercentComplete
        {
            get
            {
                this._TheJob.Get();
                return decimal.Parse(this._TheJob.Properties["PercentComplete"].Value.ToString());
            }
        }
        #endregion

        /// <summary>
        /// Sleep the calling Thread as long as the current Job State is listed among the parameter values.
        /// </summary>
        internal void WaitOn(params JobState[] jobStates)
        {
            while (jobStates.Contains(this.State))
            {
                System.Threading.Thread.Sleep(100);
            }
        }

        #region Finalize & Dispose
        public void Dispose()
        {
            try
            {
                if (this._TheJob != null)
                {
                    this._TheJob.Dispose();
                }
            }
            finally
            {
                GC.SuppressFinalize(this);
            }
        }
        ~Job()
        {
            Dispose();
        }
        #endregion
    }
}
